package io.renren.common.utils;


import io.renren.vo.FileVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;
@Component
public class FileUploadUtils {


    private static String fileSavePath;
    @Value("${file-save-path}")
    public void setFileSavePath(String path){
        fileSavePath = path;
    }


    public static FileVo upload(MultipartFile photo) {
        FileVo fileVo = null;
        try {
            if(!photo.isEmpty()) {
                 fileVo = new FileVo();

                String originalFilename = photo.getOriginalFilename();

//                if(originalFilename.endsWith(".png")||originalFilename.endsWith(".jpg")||originalFilename.endsWith(".jpeg")||originalFilename.endsWith(".mp4")) {
                    String replace = UUID.randomUUID().toString().replace("-", "");

                    String filename = replace+originalFilename;
                    fileVo.setFilename(filename);
                    fileVo.setOriginalFilename(originalFilename);
                    File file = new File(fileSavePath,filename);
                    photo.transferTo(file);

            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("上传失败");
        }
        return fileVo;
    }

    public static void showImg(String path, HttpServletResponse response){
        if(path!=null&&!path.equals("")){

            try {
                FileInputStream fis = new FileInputStream(path);
                ServletOutputStream os = response.getOutputStream();

                byte [] b = new byte[1024*8];
                while(fis.read(b)!=-1){
                    os.write(b);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}